package com.sunyur.tailor.channel.service.outer.keep.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunyur.tailor.channel.common.inner.base.MsgResultCode;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.purchase.model.*;
import com.sunyur.tailor.channel.service.inner.purchase.param.PurchaseApplyHeadByCodeParam;
import com.sunyur.tailor.channel.service.inner.purchase.param.StrategyOrderDetailParam;

import com.sunyur.tailor.channel.service.inner.purchase.service.SunyurPurchaseApplyService;
import com.sunyur.tailor.channel.service.outer.keep.param.FeishuForApprovalFormParam;
import com.sunyur.tailor.channel.service.outer.keep.param.SRMPurchaseFeishuForApprovalParam;
import com.sunyur.tailor.channel.service.outer.keep.service.KeepToFeishuService;
import com.sunyur.tailor.channel.service.outer.keep.service.WorkflowBusinessStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service("strategyOrder")
@Slf4j
public class StrategyOrderStrategyImpl implements WorkflowBusinessStrategyService {

    @Autowired
    SunyurPurchaseApplyService sunyurPurchaseApplyService;

    @Value("${feishu.strategyOrder.approvalCode}")
    private String approvalCode;

    @Autowired
    private KeepToFeishuService keepToFeishuService;


    @Override
    public ChannelResult start(MsgResultCode msgResultCode) {
        log.info("StrategyOrderStrategyImpl start msgResultCode:{}", msgResultCode);


        StrategyOrderDetailParam strategyOrderDetailParam = new StrategyOrderDetailParam();
        strategyOrderDetailParam.setPurCode(msgResultCode.getBusinessCode());


        //调用采购申请接口查询采购申请详情
        ChannelResult<StrategyOrderDetailModel> strategyOrderDetail = sunyurPurchaseApplyService.getStrategyOrderDetail(strategyOrderDetailParam);
        log.info("strategyOrderDetail: {}", JSON.toJSONString(strategyOrderDetail.getContent()));
           if(strategyOrderDetail.getCode().equals(MiddleResultEnum.FAILED.getCode())){
                return ChannelResultUtil.error(strategyOrderDetail.getCode(), strategyOrderDetail.getMessage());
            }
        //拼装请求参数
        SRMPurchaseFeishuForApprovalParam srmPurchaseFeishuForApprovalParam =new SRMPurchaseFeishuForApprovalParam();
        srmPurchaseFeishuForApprovalParam.setApproval_code(approvalCode);    //采购申请单号
        srmPurchaseFeishuForApprovalParam.setUser_id(strategyOrderDetail.getContent().getStrategyOrder().getCreator().get("workNumber").toString()); //用户id
        srmPurchaseFeishuForApprovalParam.setOpen_id(strategyOrderDetail.getContent().getStrategyOrder().getCreator().get("workNumber").toString()); //用户openId
        ArrayList formList = new ArrayList();
        FeishuForApprovalFormParam widget1=new FeishuForApprovalFormParam();
        widget1.setId("widget1");
        widget1.setType("input");
        widget1.setValue(strategyOrderDetail.getContent().getStrategyOrder().getTitle());

        FeishuForApprovalFormParam widget2=new FeishuForApprovalFormParam();
        widget2.setId("widget2");
        widget2.setType("contact");


        if(CollectionUtils.isEmpty(strategyOrderDetail.getContent().getStrategyOrderItems()))
        {
            widget2.setValue(Arrays.asList(strategyOrderDetail.getContent().getStrategyOrder().getCreator().get("workNumber").toString()));
        }else {
            List<StrategyOrderItemsVO> items = strategyOrderDetail.getContent().getStrategyOrderItems();
            List<String> upStreamCodeList =new ArrayList();
            List<String> proposerCodeList = new ArrayList<>();

            for (StrategyOrderItemsVO item : items) {
                if(!StringUtils.isEmpty(item.getUpstreamCode()))
                {
                    upStreamCodeList.add(item.getUpstreamCode());
                }
            }
            if(upStreamCodeList.size()==0)
            {

                widget2.setValue(Arrays.asList(strategyOrderDetail.getContent().getStrategyOrder().getCreator().get("workNumber").toString()));
            }else {
                for (String s : upStreamCodeList) {
                    PurchaseApplyHeadByCodeParam purchaseApplyHeadByCodeParam = new PurchaseApplyHeadByCodeParam();
                    purchaseApplyHeadByCodeParam.setApplyCode(s);
                    ChannelResult<PurchaserApplyHeadModel> purchaserApplyHeadByCode = sunyurPurchaseApplyService.getPurchaserApplyHeadByCode(purchaseApplyHeadByCodeParam);
                    proposerCodeList.add(purchaserApplyHeadByCode.getContent().getProposerCode());
                }
                List<String> disProposerCodeList = proposerCodeList.stream().distinct().collect(Collectors.toList());

                widget2.setValue(disProposerCodeList);
            }
        }

        FeishuForApprovalFormParam widget3=new FeishuForApprovalFormParam();
        widget3.setId("widget3");
        widget3.setType("textarea");
        widget3.setValue(strategyOrderDetail.getContent().getStrategyOrder().getTerms().getDemandBg()); //项目背景

        FeishuForApprovalFormParam widget4=new FeishuForApprovalFormParam();
        widget4.setId("widget4");
        widget4.setType("fieldList");
        widget4.setValue(value4(strategyOrderDetail));

        FeishuForApprovalFormParam widget5=new FeishuForApprovalFormParam();
        widget5.setId("widget5");
        widget5.setType("input");
        widget5.setValue(strategyOrderDetail.getContent().getStrategyOrder().getTypeName());

        FeishuForApprovalFormParam widget6=new FeishuForApprovalFormParam();
        widget6.setId("widget6");
        widget6.setType("textarea");
        widget6.setValue(value6(strategyOrderDetail));


        FeishuForApprovalFormParam widget7=new FeishuForApprovalFormParam();
        widget7.setId("widget7");
        widget7.setType("textarea");
        widget7.setValue(strategyOrderDetail.getContent().getStrategyOrder().getTerms().getScoreType()); //评分方式

        FeishuForApprovalFormParam widget8=new FeishuForApprovalFormParam();
        widget8.setId("widget8");
        widget8.setType("textarea");
        widget8.setValue(strategyOrderDetail.getContent().getStrategyOrder().getTerms().getTimePlan());

        FeishuForApprovalFormParam widget9=new FeishuForApprovalFormParam();
        widget9.setId("widget9");
        widget9.setType("textarea");
        widget9.setValue(strategyOrderDetail.getContent().getStrategyOrder().getRemark()
                .replaceAll("<p>", "").replaceAll("</p>", "\n")
                .replaceAll("<br>","").replaceAll("</br>","\n")
        );


        FeishuForApprovalFormParam widget10=new FeishuForApprovalFormParam();
        widget10.setId("widget10");
        widget10.setType("input");
        widget10.setValue(strategyOrderDetail.getContent().getStrategyOrder().getPurCode());

        formList.add(widget1);
        formList.add(widget2);
        formList.add(widget3);
        formList.add(widget4);
        formList.add(widget5);
        formList.add(widget6);
        formList.add(widget7);
        formList.add(widget8);
        formList.add(widget9);
        formList.add(widget10);



        srmPurchaseFeishuForApprovalParam.setForm(JSONObject.toJSONString(formList));


        //创建审批实例
        ChannelResult<Boolean> booleanChannelResult = keepToFeishuService.sRMPurchaseFeishuForApproval(msgResultCode,srmPurchaseFeishuForApprovalParam);

        return booleanChannelResult;

    }

    public List<List<FeishuForApprovalFormParam>> value4(ChannelResult<StrategyOrderDetailModel> strategyOrderDetail)
    {
        StrategyOrderDetailModel content = strategyOrderDetail.getContent();
        List first =new ArrayList();

        for (StrategyOrderItemsVO strategyOrderItem : content.getStrategyOrderItems()) {
            List two =new ArrayList();
            FeishuForApprovalFormParam widget4_1=new FeishuForApprovalFormParam();
            widget4_1.setId("widget4_1");
            widget4_1.setType("input");
            widget4_1.setValue(strategyOrderItem.getMaterialName());

            FeishuForApprovalFormParam widget4_2=new FeishuForApprovalFormParam();
            widget4_2.setId("widget4_2");
            widget4_2.setType("textarea");
            widget4_2.setValue(strategyOrderItem.getMaterialDesc().length()==0?" ":strategyOrderItem.getMaterialDesc());


            FeishuForApprovalFormParam widget4_3=new FeishuForApprovalFormParam();
            widget4_3.setId("widget4_3");
            widget4_3.setType("input");
            widget4_3.setValue(strategyOrderItem.getCount().toString());

            FeishuForApprovalFormParam widget4_4=new FeishuForApprovalFormParam();
            widget4_4.setId("widget4_4");
            widget4_4.setType("input");
            widget4_4.setValue(strategyOrderItem.getEstimatedUnitPrice().multiply(BigDecimal.valueOf(strategyOrderItem.getCount())).setScale(2,BigDecimal.ROUND_HALF_UP).toString());

            FeishuForApprovalFormParam widget4_5=new FeishuForApprovalFormParam();
            widget4_5.setId("widget4_5");
            widget4_5.setType("textarea");
            widget4_5.setValue(strategyOrderItem.getRemark());

            two.add(widget4_1);
            two.add(widget4_2);
            two.add(widget4_3);
            two.add(widget4_4);
            two.add(widget4_5);
            first.add(two);


        }



        return first;
    }

    public String  value6(ChannelResult<StrategyOrderDetailModel> strategyOrderDetail)
    {
        StrategyOrderDetailModel content = strategyOrderDetail.getContent();
        StringBuffer sb = new StringBuffer();
        for (StrategyOrderVO.SuppliersVO supplier : content.getStrategyOrder().getSuppliers()) {
            sb.append(supplier.getSupplierName()).append("\n");
        }
        return sb.toString();
    }

}
